#include "ModelProcessor.h"

#include "../RapidXML/rapidxml.hpp"
#include <fstream>

using std::cout;
using std::endl;

namespace MMM
{

ModelProcessor::ModelProcessor()
{
	name = "";
}

bool ModelProcessor::setupXML(const std::string &xmlString)
{
	try
	{
		rapidxml::xml_document<char> doc;   // character type defaults to char
		char* y = doc.allocate_string(xmlString.c_str());
		doc.parse<0>(y);					// 0 means default parse flags

		rapidxml::xml_node<>* node = doc.first_node();
		if (!node)
		{
			MMM_ERROR << "Could not parse data in XML definition" << endl;
			return false;
		}
		return _setup(node);
	}
	catch (rapidxml::parse_error& e)
	{
		MMM_ERROR << "Could not parse data in XML definition" << endl
			<< "Error message:" << e.what() << endl
			<< "Position: " << endl << e.where<char>() << endl;
	}
	catch (std::exception& e)
	{
		MMM_ERROR << "Error while parsing XML definition" << endl
			<< "Error code:" << e.what() << endl;
	}
	catch (...)
	{
		cout << "Error while parsing XML definition" << endl;
	}
	return false;
}

bool ModelProcessor::setupFile(const std::string &filename)
{
	// load file
	std::ifstream in(filename.c_str());

	if (!in.is_open())
	{
		MMM_ERROR << "Could not open XML file:" << filename << endl;
		return false;
	}

	std::stringstream buffer;
	buffer << in.rdbuf();
	std::string configXML(buffer.str());
	in.close();

	bool res = setupXML(configXML);
	if (!res)
	{
		MMM_ERROR << "Error while parsing file " << filename << endl;
	}

	return res;
}

std::string ModelProcessor::getName()
{
	return name;
}

std::string ModelProcessor::toXML(int nrTabs)
{
	std::string tab = "\t";
	std::string tabs;
	for (int i = 0; i < nrTabs; i++)
		tabs += tab;
	std::stringstream res;

	res << tabs << "<ModelProcessorConfig type='" << name << "'>" << endl;
	res << tabs << "</ModelProcessorConfig>" << endl;
	return res.str();
}

}
